import React from 'react'
import { connect } from 'dva'
import {
  Tabs,
  Form,
  Row,
  Col,
  Input,
  Cascader,
  Tag,
  Icon,
  DatePicker,
  Select,
  Button,
  Upload,
  Modal,
  Table,
  Divider,
  message,
  Tree,
} from 'antd'
import { Link, hashHistory } from 'dva/router'
import config from 'config/config'
import {isEmpty, cloneDeep, merge,pick,get,set} from 'lodash'

import { mapStateToProps } from 'utils/view_utils'
import styles from './teamMannageStyle.less'
import cx from 'classnames'
import moment from 'moment'

import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid, QueryCondition } from 'widget/Grid'

const FormItem = Form.Item
const {TextArea} = Input
const Option = Select.Option
const TabPane = Tabs.TabPane
const { TreeNode } = Tree
const confirm = Modal.confirm;

const formItemLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 20},
}

const teamMannageView = function ({dispatch, model, form, location}) {
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  const { modelObj, namespace } = model
  let {btnLoading,pageConfig1,totalNum,teamName,projectId,searchData,teamId,suitableDataList,teamModal,selectedKeys,autoExpandParent,autoExpandParent1,expandedKeys,expandedKeys1,treeData,treeData1,loading ,selectedRowKeys,pageConfig,tableData,biz, detailData} = modelObj
  let {actionType} = location.query
    // 表格配置------------开始
    const columns = [
      {
        title: '用户姓名', dataIndex: 'name', key: 'name', width: 200,
        render: function (value, item, index) {
          return item.name
        }
      }, 
      {
        title: '账号', dataIndex: 'id', key: 'id', width: 200,
        render: function (value, item, index) {
          return item.id
        }
      },
      {
        title: '状态', dataIndex: 'status', key: 'status', width: 200,
        render: function (value, item, index) {
          if(item.status ==1){
            return '启用'
          }else if(item.status ===0){
            return '禁用'
          }
        }
      },
      {
        title: 'App角色', dataIndex: 'appRoleZituo', key: 'appRoleZituo', width: 200,
        render: function (value, item, index) {
          if(item.appRoleZituo ==1){
            return '渠道经理'
          }else if(item.appRoleZituo ==2){
            return '渠道主管'
          }else if(item.appRoleZituo ==3){
            return '渠道专员'
          }else if(item.appRoleZituo ==4){
            return '小蜜蜂'
          }else if(item.appRoleZituo ==5){
            return '关键人'
          }
        }
      },
      {
        title: '团队', dataIndex: 'teamName', key: 'teamName', width: 200,
        render: function (value, item, index) {
          return item.teamName
        }
      }
    ]
    const columns1 = [
      {
        title: '姓名', dataIndex: 'name', key: 'name', width: 90,
        render: function (value, item, index) {
          return item.name
        }
      }, 
      {
        title: '账号', dataIndex: 'id', key: 'id', width: 280,
        render: function (value, item, index) {
          return item.id
        }
      },
      {
        title: '手机号', dataIndex: 'phone', key: 'phone', width: 140,
        render: function (value, item, index) {
          return item.phone
        }
      },
      {
        title: '归属', dataIndex: 'parentName', key: 'parentName', width: 80,
        render: function (value, item, index) {
          return item.parentName
        }
      },
      {
        title: '状态', dataIndex: 'status', key: 'status', width: 60,
        render: function (value, item, index) {
          if(item.status ==1){
            return '启用'
          }else if(item.status ===0){
            return '禁用'
          }
        }
      }
    ]
  
    const gridProps = {
      nameSpace: namespace,
      data: {
        columns: [].concat(columns, generateAction()),
        pageConfig, tableData,
      },
      pageChange: (pageNo, pageSize) => {
        tableData = { ...tableData, pageNo, pageSize }
        pageConfig = { ...pageConfig, pageNo, pageSize }
        changeState({ tableData, pageConfig });
      },
      scroll: { x: 1000 },
      loading
    }
    // const gridProps = {
    //   nameSpace: namespace,
    //   data: {
    //     columns: columns1,//已发布的活动不能添加和删除时间段
    //     pageConfig:{},
    //     tableData: {total: '',dataSource: tableData.dataSource},
    //   },
    //   scroll: { x: 800 },
    //   paginationFlag : false,
    //   loading
    // }
    // const gridProps1 = {
    //   nameSpace: namespace,
    //   selectedKeysChange: 'selectedKeysChange',
    //   data: {
    //     columns: columns1,//已发布的活动不能添加和删除时间段
    //     pageConfig:{},
    //     tableData: {total: '',dataSource: suitableDataList},
    //     selectedRowKeys,
    //   },
    //   scroll: { x: 800 },
    //   paginationFlag : false,
    //   loading
    // }
    const gridProps1 = {
      nameSpace: namespace,
      selectedKeysChange: 'selectedKeysChange',
      data: {
        columns: columns1,
        pageConfig:pageConfig1, tableData:suitableDataList,
        selectedRowKeys,
      },
      pageChange: (pageNo, pageSize) => {
        suitableDataList.pageNo = pageNo
        suitableDataList.pageSize = pageSize
        pageConfig1.pageNo = pageNo
        pageConfig1.pageSize = pageSize
        tableData = suitableDataList
        pageConfig = pageConfig1
        changeState({ suitableDataList, pageConfig1 });
      },
      scroll: { x: 800 },
      loading
    }

    // 表格操作区域
   function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 100,
      render: (data, record, index) => {
        var t1 = moment()
        var t3=record.endTime
        return (
          moment(t3).isBefore(t1)?null
          :
          <span>
            {((actionType != 'check'))&&
              <a href='javascript:void(0)' onClick={() => {deleteContent(data)}}>
                删除
              </a>
            }
          </span>
        )
      }
    }
  }
  //删除
  function deleteContent(item){
      confirm({
        title: '删除确认',
        content: '您真的要删除此条团队信息吗?',
        okText: '确认',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: `${namespace}/onDelete`,
            payload: {id: item.id,teamId:item.teamId}
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
  }

  //树的重装
  function renderTreeNodes(data){
    if(data.length>0){
      return data.map(item => {
        if (item.children) {
          return (
            <TreeNode title={item.title} key={item.key}>
              {renderTreeNodes(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode title={item.title} key={item.key}/>;
      });
    }
  }

  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }

  // -------------------tree----开始----

  function onExpand(Keys){
    expandedKeys =Keys
    autoExpandParent = false

    changeState({expandedKeys,autoExpandParent})
  }
  function onExpandDialog(Keys){
    expandedKeys1 =Keys
    autoExpandParent1 = false

    changeState({expandedKeys1,autoExpandParent1})
  }
  
  function onSelectTree(selectedKeys,info) {
    teamId = info.node.props.pos.length>=9?info.node.props.eventKey:''
    teamName = info.node.props.pos.length>=9?info.node.props.title:''
    dispatch({
      type: `${namespace}/getDetail`,
      payload: {id: teamId}
    })
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {teamId,teamName}
    })
  }
  function onSelectTreeDialog(selectedKeys,info){
    projectId = selectedKeys[0]
    dispatch({
      type: `${namespace}/queryUserByOrg`,
      payload: {id: selectedKeys[0]}
    })
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {projectId}
    })
  }
  
  // 搜索
  function inputSearch (value, name) {
    let obj = {[name]: value}
    searchData = Object.assign(searchData, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {searchData}
    })
  }
  function confirmDeduction(){
    dispatch({
      type: `${namespace}/queryUserByOrg`,
      payload: {}
    })
  }

 //新增拓客方式弹窗
 function updateTeam(){
  teamModal.visible = !teamModal.visible
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { teamModal}
    })
  }
  function teamSubmit(){
    dispatch({
      type: `${namespace}/addTeamUser`,
      payload: {}
    })
  }
  function teamInputSearch(value, name){
    teamName = value
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {teamName}
    })
  }
  function saveTeam(){
    if(!teamName||!teamId){
      message.warn('请选择要编辑的团队')
      return false
    }
    dispatch({
      type: `${namespace}/submit`,
      payload: {}
    })
  }
  function delTeam(){
    if(!teamName||!teamId){
      message.warn('请选择要删除的团队')
      return false
    }
    confirm({
      title: '删除确认',
      content: '您真的要删除该团队吗?',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: `${namespace}/delTeam`,
          payload: {}
        })
        form.resetFields()
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  
  if (!!modelObj.biz) {
		gridProps.biz = modelObj.biz
		gridProps.biz.syncBackCbf = (biz) => {
			dispatch({
				type: `${namespace}/updateStore`,
				payload: { biz }
			})
		}
  }
  
  return (
    <div className={cx('pageLayout')}>
      <div className={cx('public_listMain')}>
        <div className="functionButton">
          <Button type='primary' onClick={() => {
            hashHistory.push({
              pathname: '/home/expandManage/teamMannageAdd',
            })
          }}>新增团队</Button>
        </div>
      </div>
      
      <div>
        {/* <div style={{textAlign:'right'}}>
          <Button type='primary' onClick={() => updateTeam()}>编辑团队成员</Button>
        </div> */}
        
        {/*应用及资源*/}
        <CollapsiblePanels title=' ' style={{position: 'relative'}}>
          <Row className={styles.ziyuanWrap} gutter={16}>
            <Col span={8} className={styles.gridConter}>
              <div style={{height: '31px',lineHeight: '31px',border: '1px solid #f2f2f2',background: '#fbfbfb',padding: '0 6px',position:'relative'}}><span>团队组织架构</span></div>
              <div  className={styles.treeBox}>
                  <Tree
                    checkable={false}
                    onExpand={onExpand}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    onSelect={onSelectTree}
                  >
                    {renderTreeNodes(treeData)}
                  </Tree>
              </div>
            </Col>
            <Col span={16} className={styles.gridConter}>
              <div>
                <div style={{marginBottom:'14px',paddingLeft: '12px',position: 'relative'}}>
                  <div><span>团队名称</span><Input style={{width:'260px',marginLeft: '12px'}} value={teamName} placeholder="请输入团队名称" onChange={(e) => { teamInputSearch(e.target.value, 'teamName') }} /></div>
                  <div style={{position: 'absolute',right: 0,top: 0}}>
                  <Button style={{marginRight: '12px'}} type='primary' onClick={() => saveTeam()}>保存</Button>
                  <Button style={{marginRight: '12px'}} type='primary' onClick={() => updateTeam()}>编辑团队成员</Button>
                  <Button type='primary' onClick={() => delTeam()}>删除团队</Button>
                  </div>
                </div>
                <div style={{height: '31px',lineHeight: '31px',border: '1px solid #f2f2f2',background: '#fbfbfb',padding: '0 6px',textAlign:'center'}}><span>用户列表</span></div>
                 <Grid {...gridProps} />
              </div> 
            </Col>
          </Row>
        </CollapsiblePanels>
      </div>
      <Modal
          title="编辑团队成员"
          visible={teamModal.visible}
          width='1200px'
          destroyOnClose={true}
          // onOk={() => { teamSubmit() }}
          onCancel={() => { updateTeam() }}
          footer={null}
        >
        <div>
          <Row className={styles.ziyuanWrap} gutter={16}>
            <Col span={8} className={styles.gridConter}>
              <div style={{height: '31px',lineHeight: '31px',border: '1px solid #f2f2f2',background: '#fbfbfb',padding: '0 6px',position:'relative'}}><span>团队组织架构</span></div>
              <div  className={styles.treeBox}>
                  <Tree
                    checkable={false}
                    onExpand={onExpandDialog}
                    expandedKeys={expandedKeys1}
                    autoExpandParent={autoExpandParent1}
                    onSelect={onSelectTreeDialog}
                  >
                    {renderTreeNodes(treeData1)}
                  </Tree>
              </div>
            </Col>
            <Col span={16} className={styles.gridConter}>
              <div>
                <div style={{marginBottom:'12px'}}>
                  <Row>
                    <Col span={6} style={{marginRight:'10px'}}>
                    <Input placeholder="请输入姓名" onChange={(e) => { inputSearch(e.target.value, 'name') }}/>
                    </Col>
                    <Col span={6} style={{marginRight:'10px'}}>
                    <Input placeholder="请输入账号" onChange={(e) => { inputSearch(e.target.value, 'loginName') }}/>
                    </Col>
                    <Col span={6} style={{marginRight:'10px'}}>
                    <Input placeholder="请输入手机号" onChange={(e) => { inputSearch(e.target.value, 'phone') }} />
                    </Col>
                    <Col span={4}>
                      <Button type='primary' onClick={() => {confirmDeduction()}}>查询</Button>
                    </Col>
                  </Row>
                </div>
              {/* <div style={{height: '31px',lineHeight: '31px',border: '1px solid #f2f2f2',background: '#fbfbfb',padding: '0 6px',textAlign:'center'}}><span>用户列表</span></div> */}
                 <Grid {...gridProps1} />
                 {/* <Table dataSource={suitableDataList} columns={columns1} scroll={{ x: 800 }}/> */}
              </div> 
            </Col>
          </Row>
          <div style={{textAlign: 'center'}}>
              <Button type='primary' loading={btnLoading}  style={{marginRight:'20px'}} onClick={() => {teamSubmit()}}>确认</Button>
              <Button onClick={() => {updateTeam() }}>取消</Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(teamMannageView))

